package com.JZ.QM.service.impl;

import com.JZ.QM.common.dao.UserAccountDao;
import com.JZ.QM.common.entity.UserAccountEntity;
import com.JZ.QM.service.UserInfoService;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.JZ.QM.common.utils.PageUtils;
import com.JZ.QM.common.utils.Query;

import com.JZ.QM.common.dao.UserInfoDao;
import com.JZ.QM.common.entity.UserInfoEntity;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Slf4j
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoDao, UserInfoEntity> implements UserInfoService {

    @Resource
    UserInfoDao userInfoDao;

    @Resource
    UserAccountDao userAccountDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) throws Exception {
        IPage<UserInfoEntity> page = this.page(
                new Query<UserInfoEntity>().getPage(params),
                new QueryWrapper<UserInfoEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    public boolean sendCode(String phoneNumber, String code ,Integer identification) throws ClientException {
        // 短信API产品名称
        String product = "Dysmsapi";

        // 短信API产品域名
        String domain = "dysmsapi.aliyuncs.com";

        // accessKeyId
        String accessKeyId = "LTAI4G3vrszPdqh7xTcpyEyb";

        //accessKeySecret
        String accessKeySecret = "OdMKUDZF9MZT5V9z5YHFd6tijiDTyf";

        // 短信签名
        String SignName = "启明平台";

        // 短信模板
        String TemplateCode = "";

        if(identification == 1){
            //登录验证码模板
            TemplateCode = "SMS_193512620";
        }else{
            //注册验证码模板
            TemplateCode = "SMS_193507671";
        }


        IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
                accessKeyId, accessKeySecret);

        IAcsClient acsClient = new DefaultAcsClient(profile);

        // 组装请求对象
        SendSmsRequest request = new SendSmsRequest();

        // 使用post提交
        request.setSysMethod(MethodType.POST);

        // 待发送手机号。
        request.setPhoneNumbers(phoneNumber);

        // 短信签名
        request.setSignName(SignName);

        // 短信模板
        request.setTemplateCode(TemplateCode);

        //此处的code和短信模板中的${code}对应
        request.setTemplateParam("{ \"code\":\""+code+"\"}");

        SendSmsResponse sendSmsResponse = acsClient.getAcsResponse(request);

        log.info(sendSmsResponse.getCode());
        // 请求成功
        if (sendSmsResponse.getCode() != null
                && sendSmsResponse.getCode().equals("OK")) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 验证用户账号是否已经存在
     *
     * @param phoneNumber
     * @return
     */
    @Override
    public boolean validUserAccount(String phoneNumber) {
        //验证flag,true为无重复，false为有重复
        boolean validFlag = true;

        //查询条件构造器
        QueryWrapper<UserInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account",phoneNumber);

        //查询存在的数量
        Integer Number = userInfoDao.selectCount(queryWrapper);

        if(Number > 0){
            validFlag = false;
        }else {
            validFlag = true;
        }

        return validFlag;
    }

    /**
     * 获取需要的cookie信息
     *
     * @param phoneNumber
     * @return
     */
    @Override
    public Map<String, String> getCookie(String phoneNumber) {
        //存储cookie的Map
        Map<String,String> cookieMap = new HashMap<>();

        //查询条件构造器
        QueryWrapper<UserInfoEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_account",phoneNumber);

        UserInfoEntity userInfoEntity = userInfoDao.selectOne(queryWrapper);

        if(userInfoEntity != null){
            //设置用户id
            cookieMap.put("id", String.valueOf(userInfoEntity.getUserId()));
            //设置用户昵称
            cookieMap.put("nickName",userInfoEntity.getNickName());
            //设置用户头像
            cookieMap.put("images",userInfoEntity.getUserImages());
            //设置用户风险等级
            cookieMap.put("riskLevel",userInfoEntity.getUserRisk());
        }
        return cookieMap;
    }

    /**
     * 注册保存操作
     *
     * @param phoneNumber
     * @return
     */
    @Transactional
    @Override
    public boolean register(String phoneNumber) {
        //保存用户信息flag
        int saveUserFlag = 1;
        //用户id
        Long id = Long.valueOf(0);
        //构造用户昵称
        String nickName = UUID.randomUUID().toString().substring(0,10);

        //创建用户基本信息
        UserInfoEntity userInfoEntity = new UserInfoEntity();
        userInfoEntity.setUserAccount(phoneNumber);
        userInfoEntity.setNickName(nickName);
        //设置用户风险等级为默认0
        userInfoEntity.setUserRisk(String.valueOf(0));

        saveUserFlag = userInfoDao.insert(userInfoEntity);

        if(1 == saveUserFlag ){
            return true;
        }else {
            return false;
        }
    }
}